package com.ruoyi.duanju.service.impl;

import cn.hutool.core.util.HashUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.WaitForSelectorState;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.duanju.domain.DjDuanju;
import com.ruoyi.duanju.mapper.DjDuanjuMapper;
import com.ruoyi.duanju.service.IPlaywrightService;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

@Service
public class PlaywrightServiceImpl implements IPlaywrightService {

    private static final Logger log = LoggerFactory.getLogger(PlaywrightServiceImpl.class);

    Playwright playwright;
    Browser browser;

    ExecutorService executorService = Executors.newFixedThreadPool(10);
    private  Path STATE_PATH = Paths.get("cookie.json");
//    private static Path STATE_PATH;
//
//    static {
//        try {
//            STATE_PATH = ResourceUtils.getFile("classpath:cookie.json").toPath();
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        }
//    }


    @Autowired
    DjDuanjuMapper duanjuMapper;

    @Override
    public List<DjDuanju> search(String title) {
        String res = HttpUtil.get("https://www.duanju.click/api/short/quark", new HashMap<String, Object>() {{
            put("text", title);
        }});
        log.info("url:{},title:{},res:{}", "https://www.duanju.click/api/short/quark", title, res);
        if (StringUtils.isNotEmpty(res)) {

            JSONObject object = JSONObject.parseObject(res);
            if (object.getIntValue("code") == 200) {
                JSONArray dataArray = object.getJSONArray("data");
                if(dataArray.size() == 0){
                    return new ArrayList<>();
                }
                JSONObject data = dataArray.getJSONObject(0);
                String searchTitle = data.getString("name");
                String searchLink = data.getString("link");
//                    String time = data.getString("time");
                try (Playwright playwright = Playwright.create()) {
                        Browser browser = playwright.chromium().launch();
//                    Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(150));
                    BrowserContext context;
                    if (!Files.exists(STATE_PATH)) {
                        context = browser.newContext(new Browser.NewContextOptions().setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"));
                        //保存状态
                        context.storageState(new BrowserContext.StorageStateOptions().setPath(STATE_PATH));
                    } else {
                        //加载状态
                        context = browser.newContext(new Browser.NewContextOptions()
                                .setStorageStatePath(STATE_PATH));
                    }

                    Page page = context.newPage();

                    page.navigate(searchLink);
                    page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("保存到网盘")).click();
//                    if(page.locator("#QKVIP_8uvhzsjc6wk").contentFrame().getByText("空间不足，立即扩容").isVisible()){
//                        throw new RuntimeException("空间已满，请清理");
//                    }
//                    if(page.locator("iframe").contentFrame().locator(".modal-mask").isVisible()){
//                        throw new RuntimeException("空间已满，请清理");
//                    }
                    if(page.locator("#QKVIP_ukx81vxqtii").contentFrame().locator("#lite-modal-PayModal img").isVisible()){
                        throw new RuntimeException("空间已满，请清理");
                    }


                    // 监听特定的请求模式
                    page.route("**/clouddrive/task**", route -> {
                        System.out.println("捕捉到请求");
                        APIResponse response = route.fetch();
                        if(response.status() == 200){
                            System.out.println("请求成功");
                        }

                        String tempRes = response.text();
                        JSONObject tempObj = JSONObject.parseObject(tempRes);
                        if(tempObj.getIntValue("code") == 32003){
                            System.out.println("存储空间已满");
                            throw new RuntimeException("空间已满，请清理");
                        }
                    });

//page.pause();
//                    page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("立即查看")).click();
                    Page page1 = page.waitForPopup(() -> {
                        page.getByRole(AriaRole.IMG, new Page.GetByRoleOptions().setName("夸克网盘")).click();
                    });
                    page1.getByText("来自：分享").click();
                    page1.locator(".hover-oper-list > div:nth-child(2)").first().click();
                    page1.locator("label").filter(new Locator.FilterOptions().setHasText("永久有效")).click();

                    page1.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("创建分享")).click();
                    Locator inputLocator = page1.getByRole(AriaRole.DIALOG, new Page.GetByRoleOptions().setName("分享文件")).locator("input.ant-input");
                    inputLocator.waitFor(new Locator.WaitForOptions().setTimeout(5000));
                    String shareUrl = inputLocator.first().getAttribute("value");
                    System.out.println("Thread:" + Thread.currentThread() + " shareUrl: " + shareUrl);
//browser.close();


                    //新建
                    DjDuanju djDuanju = new DjDuanju();
                    djDuanju.setTitle(searchTitle);
                    djDuanju.setShareUrl(shareUrl);
                    djDuanju.setCreateTime(new Date());
                    duanjuMapper.insertDjDuanju(djDuanju);
                    return Arrays.asList(djDuanju);

//                        context.storageState(new BrowserContext.StorageStateOptions().setPath(STATE_PATH));


                }
            }
        }
        return new ArrayList<>();
    }

    private CompletableFuture<R> fetchWithWait(String title) {
        return CompletableFuture.supplyAsync(() -> {
//            搜索 https://www.duanju.click/
            String res = HttpUtil.get("https://www.duanju.click/api/short/quark", new HashMap<String, Object>() {{
                put("text", title);
            }});
            log.info("url:{},title:{},res:{}", "https://www.duanju.click/api/short/quark", title, res);
            if (StringUtils.isNotEmpty(res)) {
                JSONObject object = JSONObject.parseObject(res);
                if (object.getIntValue("code") == 200) {
                    JSONArray dataArray = object.getJSONArray("data");
                    JSONObject data = dataArray.getJSONObject(0);
                    String searchTitle = data.getString("name");
                    String searchLink = data.getString("link");
//                    String time = data.getString("time");

                    try (Playwright playwright = Playwright.create()) {
//                        Browser browser = playwright.chromium().launch();
                        Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(50));
                        BrowserContext context;
                        if (!Files.exists(STATE_PATH)) {
                            context = browser.newContext(new Browser.NewContextOptions().setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"));
                            //保存状态
                            context.storageState(new BrowserContext.StorageStateOptions().setPath(STATE_PATH));
                        } else {
                            //加载状态
                            context = browser.newContext(new Browser.NewContextOptions()
                                    .setStorageStatePath(Paths.get("xg.json")));
                        }

                        Page page = context.newPage();

                        page.navigate(searchLink);
                        System.out.println("Thread:" + Thread.currentThread() + " title: " + page.title());


//                        context.storageState(new BrowserContext.StorageStateOptions().setPath(STATE_PATH));
                        browser.close();

                    }
                }
            }
            return R.ok();
        }, executorService);
    }

//    @Override
//    public R search(String title) {
//        Callable<JSONObject> callable = () -> {
////搜索 https://www.duanju.click/
//            String res = HttpUtil.get("https://www.duanju.click/api/short/quark", new HashMap<String, Object>() {{
//                put("text", title);
//            }});
//            log.info("url:{},title:{},res:{}", "https://www.duanju.click/api/short/quark", title, res);
//            if (StringUtils.isNotEmpty(res)) {
//                JSONObject object = JSONObject.parseObject(res);
//                if (object.getIntValue("code") == 200) {
//                    JSONArray dataArray = object.getJSONArray("data");
//                    JSONObject data = dataArray.getJSONObject(0);
//                    String searchTitle = data.getString("name");
//                    String searchLink = data.getString("link");
////                    String time = data.getString("time");
//
//                    //执行分享操作
//                    // 每个线程创建独立实例
//                    try (Playwright playwright = Playwright.create()) {
////                        Browser browser = playwright.chromium().launch();
//                        Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(50));
//                        BrowserContext context;
//                        if (!Files.exists(STATE_PATH)) {
//                            context = browser.newContext(new Browser.NewContextOptions().setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"));
//                            //保存状态
//                            context.storageState(new BrowserContext.StorageStateOptions().setPath(STATE_PATH));
//                        } else {
//                            //加载状态
//                            context = browser.newContext(new Browser.NewContextOptions()
//                                    .setStorageStatePath(Paths.get("xg.json")));
//                        }
//
//                        Page page = context.newPage();
//
//                        page.navigate(searchLink);
//                        System.out.println("Thread:" + Thread.currentThread() + " title: " + page.title());
//
//
//                        context.storageState(new BrowserContext.StorageStateOptions().setPath(STATE_PATH));
//                        browser.close();
//                    }
//
//                    return data;
////                    return R.ok(object.getJSONObject("data"));
//                } else {
//                    log.error("搜索错误：" + res);
//                }
//            }
//            return null;
//        };
//        Future<JSONObject> future = executorService.submit(callable);
//
//
//        try {
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return R.ok("未搜索到结果");
//
//    }

//    @PostConstruct
//    public void init() {
//        System.out.println("playwright初始化");
//        try (Playwright playwright = Playwright.create()) {
//            Browser browser = playwright.webkit().launch();
//            Page page = browser.newPage();
//            page.navigate("https://playwright.dev/");
//            page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example.png")));
//        }
//    }

}
